/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.globussoft.xml;

/**
 *
 * @author Dj
 */
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class XmlPerformanceStore
{
    
        private boolean bandwidth;
        private int limit;
        private boolean throttle;
        private boolean throttle_hour;
        private int throttle_from;
        private int throttle_to;
        Document dom=null;
        private String projectName="Pomblast";
        public XmlPerformanceStore(){
          projectName=SettingsXml.getProjectName();
        }
     public boolean getBandwidth()
     {
          return bandwidth;

     }
    public void setBandwidth(boolean bandwidth) {

            this.bandwidth = bandwidth;
         }

      public int getLimit() {

            return limit;

      }

      public void setLimit(int limit) {

            this.limit = limit;

      }

      public boolean getThrottle() {

            return throttle;

      }

      public void setThrottle(boolean throttle) {

            this.throttle = throttle;

      }
       public boolean getThrottlehour() {

            return throttle_hour;

      }
    public void setThrottlehour(boolean throttle_hour) {

            this.throttle_hour = throttle_hour;
         }

      public int getThrottlefrom() {

            return throttle_from;

      }

      public void setThrottlefrom(int throttle_from) {

            this.throttle_from = throttle_from;

      }

      public int getThrottleto() {

            return throttle_to;

      }

      public void setThrottleto(int throttle_to) {

            this.throttle_to = throttle_to;

      }

       public  void writeGeneralXml(String filename) throws ParserConfigurationException{

           //create a list to hold the data
             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

            try {

                  DocumentBuilder db = dbf.newDocumentBuilder();

                  dom = db.newDocument();

                  Element rootElement = dom.createElement("General-Settings");

                 // dom.appendChild(rootElement);

                  Element generalElement = dom.createElement("Performance");

                  generalElement=createGeneralElement(generalElement,"Bandwidth",""+bandwidth);
                  generalElement=createGeneralElement(generalElement,"Limit",""+limit);
                  generalElement=createGeneralElement(generalElement,"Throttle",""+throttle);
                  generalElement=createGeneralElement(generalElement,"Throttle_Hour",""+throttle_hour);
                  generalElement=createGeneralElement(generalElement,"Throttle_From",""+throttle_from);
                  generalElement=createGeneralElement(generalElement,"Throttle_To",""+throttle_to);
                  rootElement.appendChild(generalElement);
                  dom.appendChild(rootElement);

                 try{
                  printToFile(dom,filename);
                 }catch(Exception ex){ex.printStackTrace();}



            }catch(ParserConfigurationException pce) {
                   pce.printStackTrace();
                //  System.out.println("Error while trying to instantiate DocumentBuilder " + pce);

                  System.exit(1);

             }


      }

               /**
	 * Helper method which creates a XML element
	 * @param xmlgeneralstore The SetXmlGeneralStore for which we need to create an xml representation
	 * @return XML element snippet representing a SetXmlGeneralStore
	 */

      private Element createGeneralElement(Element generalElement,String property,String value)
      {


          //create Status element and Status text node and attach it to generalElement
            Element statusElement = dom.createElement(property);

            Text statusText = dom.createTextNode(value);

            statusElement.appendChild(statusText);

            generalElement.appendChild(statusElement);


            return generalElement;

      }

       private void printToFile(Document dom,String filename) throws FileNotFoundException, IOException{
           try
            {

                 OutputFormat format = new OutputFormat(dom);
                  format.setIndenting(true);
                  //URL mySource = XmlGeneralStore.class.getProtectionDomain().getCodeSource().getLocation();
                //  File sourceFile = new File(".");
                 boolean success;
                 String    source=System.getProperty("user.home");
                 String dir=source+"\\"+projectName;
                 File sourceFile = new File(dir);
                 if(!sourceFile.exists())
                 {
                     success=new File(dir).mkdir();
                 }


                // attach text file to application directory(.class file)
                  String xmlfile = dir+"\\"+filename;

               //to generate output to console use this serializer

              //XMLSerializer serializer = new XMLSerializer(System.out, format);

             //to generate a file output use fileoutputstream instead of system.out

                  XMLSerializer serializer = new XMLSerializer(new FileOutputStream(new File(xmlfile)), format);
                  serializer.serialize(dom);

              } catch(IOException ie)
              {
                 ie.printStackTrace();
              }

      }

       //reading the xml file code her
public void ReadGeneralXml(String filename)
{
   // String storegenerralxml[]=new String[10];
  try {
      // URL mySource = XmlGeneralStore.class.getProtectionDomain().getCodeSource().getLocation();
      File sourceFile = new File(".");
     // attach text file to application directory(.class file)
      //String xmlfile = sourceFile.getAbsolutePath()+"\\"+"generalsettings.xml";
	  boolean success;
      String    source=System.getProperty("user.home");
      String dir=source+"\\"+projectName;
      File fXmlFile = new File(dir+"\\"+filename);
      if(fXmlFile.isFile())
      {
	  DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	  DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	  Document doc = dBuilder.parse(fXmlFile);
	  doc.getDocumentElement().normalize();

	 // System.out.println("General Settings :" + doc.getDocumentElement().getNodeName());
	  NodeList nList = doc.getElementsByTagName("Performance");
	//  System.out.println("-----------------------");

	  for (int temp = 0; temp < nList.getLength(); temp++) {

	    Node nNode = nList.item(temp);

	    if (nNode.getNodeType() == Node.ELEMENT_NODE) {

	      Element eElement = (Element) nNode;

//	     storegenerralxml[0]= getTagValue("Bandwidth",eElement);
//	     storegenerralxml[1]= getTagValue("Limit",eElement);
//	     storegenerralxml[2]=getTagValue("Throttle",eElement).trim();
         String bandwidthtemp=getTagValue("Bandwidth",eElement).trim();
         if(bandwidthtemp.equals("false"))
             bandwidth=false;
         else
             bandwidth=true;
          String limittemp=getTagValue("Limit",eElement);
         limit=Integer.parseInt(limittemp);
          String throttletemp=getTagValue("Throttle",eElement).trim();
          if(throttletemp.equals("false"))
             throttle=false;
          else
              throttle=true;
           String throttle_hourtemp= getTagValue("Throttle_Hour",eElement);
           if(throttle_hourtemp.equals("false"))
             throttle_hour=false;
          else
              throttle_hour=true;
         String throttle_tromtemp= getTagValue("Throttle_From",eElement);
         throttle_from=Integer.parseInt(throttle_tromtemp);
         String throttle_totemp=getTagValue("Throttle_To",eElement).trim();
         throttle_to=Integer.parseInt(throttle_totemp);

	    }
      }
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
    //return storegenerralxml;
}

private static String getTagValue(String sTag, Element eElement)
 {
	  NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
	  Node nValue = (Node) nlList.item(0);

	  return nValue.getNodeValue();

 }

}

